package com.kwk.messagepushding.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class MyRunnableTask implements Runnable {
    private final Socket socket;

    public  MyRunnableTask(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        // 调用新方法
        try {
            handleClient(socket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }



    public void handleClient(Socket socket)  throws IOException {
        //接收数据
        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            String data = bytesToHex(buffer, length);
            System.out.println("客户端：" + socket.getInetAddress().getHostAddress()+":"+socket.getPort() + ",接收数据：" + data);
            if (data.startsWith("0000000000")) {
                int decimal = Integer.parseInt(data.substring(12, 14), 16);
                System.out.println(decimal);
            }
//                    if(data.startsWith("1111111111")){
//                        // 创建Modbus TCP客户端
//                        ModbusTCPMaster  master = new ModbusTCPMaster("127.0.0.1", transPondPort);
//                        master.connect(); // 建立连接
//                        // 读取保持寄存器
//                        int ref = 0; // 起始地址
//                        int count = 10; // 读取的寄存器数量
//                        Register[] registers = master.readMultipleRegisters(ref, count);
//                        // 输出读取到的数据
//                        for (int i = 0; i < registers.length; i++) {
//                            System.out.println("Register " + (ref + i) + " = " + registers[i].getValue());
//                        }
//                        System.out.println(data.substring(12,14));
//                    }

        }
    }

    // 辅助方法：将字节数组转换为十六进制字符串

    private static String bytesToHex(byte[] bytes, int length) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String hex = Integer.toHexString(0xff & bytes[i]);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}